import Foundation
import UIKit
import CoreLocation
import UserNotifications
import AudioToolbox
import SystemConfiguration

/**
 * iOS平台适配器
 */
class IOSPlatformAdapter: NSObject, PlatformAdapterProtocol {
    
    private let locationManager = CLLocationManager()
    private var permissionCallbacks: [String: (Bool) -> Void] = [:]
    
    override init() {
        super.init()
        setupLocationManager()
    }
    
    // MARK: - 权限管理
    
    func requestPermissions(permissions: [String], callback: @escaping ([String: Bool]) -> Void) {
        var results: [String: Bool] = [:]
        let group = DispatchGroup()
        
        for permission in permissions {
            group.enter()
            requestSinglePermission(permission: permission) { granted in
                results[permission] = granted
                group.leave()
            }
        }
        
        group.notify(queue: .main) {
            callback(results)
        }
    }
    
    func checkPermission(permission: String) -> Bool {
        switch permission {
        case "camera":
            return AVCaptureDevice.authorizationStatus(for: .video) == .authorized
        case "location":
            return CLLocationManager.authorizationStatus() == .authorizedWhenInUse ||
                   CLLocationManager.authorizationStatus() == .authorizedAlways
        case "notifications":
            var isAuthorized = false
            let semaphore = DispatchSemaphore(value: 0)
            UNUserNotificationCenter.current().getNotificationSettings { settings in
                isAuthorized = settings.authorizationStatus == .authorized
                semaphore.signal()
            }
            semaphore.wait()
            return isAuthorized
        case "microphone":
            return AVAudioSession.sharedInstance().recordPermission == .granted
        case "photos":
            return PHPhotoLibrary.authorizationStatus() == .authorized
        default:
            return false
        }
    }
    
    func openAppSettings() {
        if let settingsUrl = URL(string: UIApplication.openSettingsURLString) {
            if UIApplication.shared.canOpenURL(settingsUrl) {
                UIApplication.shared.open(settingsUrl)
            }
        }
    }
    
    // MARK: - 通知管理
    
    func showNotification(title: String, content: String, channelId: String, priority: NotificationPriority) {
        let content = UNMutableNotificationContent()
        content.title = title
        content.body = content
        content.sound = UNNotificationSound.default
        
        // 设置优先级
        switch priority {
        case .low:
            content.interruptionLevel = .passive
        case .default:
            content.interruptionLevel = .active
        case .high:
            content.interruptionLevel = .timeSensitive
        case .max:
            content.interruptionLevel = .critical
        }
        
        let request = UNNotificationRequest(
            identifier: UUID().uuidString,
            content: content,
            trigger: nil
        )
        
        UNUserNotificationCenter.current().add(request)
    }
    
    // MARK: - 震动和声音
    
    func vibrate(pattern: [TimeInterval], repeat: Int) {
        // iOS使用Haptic Feedback
        if #available(iOS 10.0, *) {
            let impactFeedback = UIImpactFeedbackGenerator(style: .medium)
            impactFeedback.impactOccurred()
        } else {
            AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
        }
    }
    
    func playSound(soundType: SoundType) {
        var soundID: SystemSoundID = 0
        
        switch soundType {
        case .orderReceived:
            soundID = 1007 // SMS received sound
        case .messageReceived:
            soundID = 1003 // SMS received sound
        case .paymentSuccess:
            soundID = 1001 // Mail sent sound
        case .error:
            soundID = 1006 // Low power sound
        case .success:
            soundID = 1001 // Mail sent sound
        }
        
        AudioServicesPlaySystemSound(soundID)
    }
    
    // MARK: - 设备信息
    
    func getDeviceInfo() -> DeviceInfo {
        let device = UIDevice.current
        let screen = UIScreen.main
        
        return DeviceInfo(
            platform: "iOS",
            version: device.systemVersion,
            model: device.model,
            manufacturer: "Apple",
            deviceId: getDeviceIdentifier(),
            screenWidth: Int(screen.bounds.width * screen.scale),
            screenHeight: Int(screen.bounds.height * screen.scale),
            density: Float(screen.scale)
        )
    }
    
    // MARK: - 分享和外部应用
    
    func shareContent(content: String, title: String, viewController: UIViewController) {
        let activityViewController = UIActivityViewController(
            activityItems: [content],
            applicationActivities: nil
        )
        
        // iPad适配
        if let popover = activityViewController.popoverPresentationController {
            popover.sourceView = viewController.view
            popover.sourceRect = CGRect(x: viewController.view.bounds.midX,
                                      y: viewController.view.bounds.midY,
                                      width: 0, height: 0)
        }
        
        viewController.present(activityViewController, animated: true)
    }
    
    func openURL(url: String) {
        if let url = URL(string: url) {
            if UIApplication.shared.canOpenURL(url) {
                UIApplication.shared.open(url)
            }
        }
    }
    
    func makePhoneCall(phoneNumber: String) {
        if let url = URL(string: "tel://\(phoneNumber)") {
            if UIApplication.shared.canOpenURL(url) {
                UIApplication.shared.open(url)
            }
        }
    }
    
    func sendSMS(phoneNumber: String, message: String) {
        if let url = URL(string: "sms:\(phoneNumber)&body=\(message.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "")") {
            if UIApplication.shared.canOpenURL(url) {
                UIApplication.shared.open(url)
            }
        }
    }
    
    func openMap(latitude: Double, longitude: Double, label: String) {
        let coordinate = "\(latitude),\(longitude)"
        let encodedLabel = label.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
        
        // 尝试打开Apple Maps
        if let url = URL(string: "http://maps.apple.com/?q=\(encodedLabel)&ll=\(coordinate)") {
            if UIApplication.shared.canOpenURL(url) {
                UIApplication.shared.open(url)
                return
            }
        }
        
        // 备选：Google Maps
        if let url = URL(string: "https://maps.google.com/maps?q=\(coordinate)(\(encodedLabel))") {
            if UIApplication.shared.canOpenURL(url) {
                UIApplication.shared.open(url)
            }
        }
    }
    
    // MARK: - 网络状态
    
    func getNetworkType() -> NetworkType {
        var zeroAddress = sockaddr_in()
        zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
        zeroAddress.sin_family = sa_family_t(AF_INET)
        
        guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
            $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
                SCNetworkReachabilityCreateWithAddress(nil, $0)
            }
        }) else {
            return .none
        }
        
        var flags: SCNetworkReachabilityFlags = []
        if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
            return .none
        }
        
        if flags.contains(.reachable) == false {
            return .none
        } else if flags.contains(.isWWAN) == true {
            return .cellular
        } else {
            return .wifi
        }
    }
    
    func isNetworkAvailable() -> Bool {
        return getNetworkType() != .none
    }
    
    // MARK: - 电池状态
    
    func getBatteryLevel() -> Int {
        UIDevice.current.isBatteryMonitoringEnabled = true
        return Int(UIDevice.current.batteryLevel * 100)
    }
    
    func isLowPowerMode() -> Bool {
        return ProcessInfo.processInfo.isLowPowerModeEnabled
    }
    
    // MARK: - 私有方法
    
    private func setupLocationManager() {
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
    }
    
    private func requestSinglePermission(permission: String, callback: @escaping (Bool) -> Void) {
        switch permission {
        case "camera":
            AVCaptureDevice.requestAccess(for: .video) { granted in
                DispatchQueue.main.async {
                    callback(granted)
                }
            }
        case "location":
            permissionCallbacks["location"] = callback
            locationManager.requestWhenInUseAuthorization()
        case "notifications":
            UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, _ in
                DispatchQueue.main.async {
                    callback(granted)
                }
            }
        case "microphone":
            AVAudioSession.sharedInstance().requestRecordPermission { granted in
                DispatchQueue.main.async {
                    callback(granted)
                }
            }
        case "photos":
            PHPhotoLibrary.requestAuthorization { status in
                DispatchQueue.main.async {
                    callback(status == .authorized)
                }
            }
        default:
            callback(false)
        }
    }
    
    private func getDeviceIdentifier() -> String {
        return UIDevice.current.identifierForVendor?.uuidString ?? "unknown"
    }
}

// MARK: - CLLocationManagerDelegate

extension IOSPlatformAdapter: CLLocationManagerDelegate {
    
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        if let callback = permissionCallbacks["location"] {
            let granted = status == .authorizedWhenInUse || status == .authorizedAlways
            callback(granted)
            permissionCallbacks.removeValue(forKey: "location")
        }
    }
}

// MARK: - iOS特定扩展

class IOSExtensions {
    
    /**
     * 检查是否支持Touch ID/Face ID
     */
    static func supportsBiometricAuthentication() -> Bool {
        if #available(iOS 8.0, *) {
            let context = LAContext()
            var error: NSError?
            return context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error)
        }
        return false
    }
    
    /**
     * 获取生物识别类型
     */
    static func getBiometricType() -> BiometricType {
        if #available(iOS 11.0, *) {
            let context = LAContext()
            var error: NSError?
            
            if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
                switch context.biometryType {
                case .touchID:
                    return .touchID
                case .faceID:
                    return .faceID
                default:
                    return .none
                }
            }
        }
        return .none
    }
    
    /**
     * 获取应用版本信息
     */
    static func getAppVersionInfo() -> AppVersionInfo {
        let bundle = Bundle.main
        let version = bundle.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "unknown"
        let build = bundle.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "0"
        let bundleId = bundle.bundleIdentifier ?? "unknown"
        
        return AppVersionInfo(
            versionName: version,
            versionCode: Int(build) ?? 0,
            packageName: bundleId,
            firstInstallTime: 0, // iOS不提供此信息
            lastUpdateTime: 0    // iOS不提供此信息
        )
    }
    
    /**
     * 检查应用是否在前台
     */
    static func isAppInForeground() -> Bool {
        return UIApplication.shared.applicationState == .active
    }
}

enum BiometricType {
    case none
    case touchID
    case faceID
}
